<template>
  <div class="appointment-schedule">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>预约管理</span>
          <div class="header-operations">
            <el-select v-model="selectedSubject" placeholder="选择培训科目" clearable>
              <el-option label="科目二" value="subject2" />
              <el-option label="科目三" value="subject3" />
            </el-select>
            <el-button type="primary" @click="dialogVisible = true">新建预约</el-button>
            <el-button @click="checkConflicts">检查冲突</el-button>
          </div>
        </div>
      </template>

      <div class="schedule-container">
        <!-- 新建预约表单已移除，改为使用抽屉式 -->
        
        <!-- 日历视图 -->
        <div class="calendar-view">
          <el-calendar v-model="currentDate">
            <template #header="{ date }">
              <div class="calendar-header">
                <el-button-group>
                  <el-button @click="selectToday">今天</el-button>
                  <el-button @click="changeMonth(-1)">上个月</el-button>
                  <el-button @click="changeMonth(1)">下个月</el-button>
                </el-button-group>
                <!-- <span class="calendar-title">{{ date ? `${date.getFullYear()}年 ${date.getMonth() + 1}月` : '' }}</span> -->
              </div>
            </template>
            <template #date-cell="{ data }">
              <div class="calendar-cell">
                <div class="date-info">
                  <span>{{ data.day.split('-').slice(-1)[0] }}</span>
                  <el-tag
                    v-if="getDateAppointments(data.day).length"
                    size="small"
                    type="success"
                  >
                    {{ getDateAppointments(data.day).length }}个预约
                  </el-tag>
                </div>
                <div class="appointment-list">
                  <div
                    v-for="appointment in getDateAppointments(data.day)"
                    :key="appointment.id"
                    class="appointment-item"
                    :class="getAppointmentClass(appointment)"
                    @click="handleAppointmentClick(appointment)"
                  >
                    {{ appointment.time }}
                    {{ appointment.studentName }}
                  </div>
                </div>
              </div>
            </template>
          </el-calendar>
        </div>

        <!-- 预约详情侧边栏 -->
        <el-drawer
          v-model="drawerVisible"
          title="预约详情"
          size="500px"
          :destroy-on-close="true"
        >
          <div class="appointment-detail" v-if="selectedAppointment">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="预约编号">{{ selectedAppointment.id }}</el-descriptions-item>
              <el-descriptions-item label="预约日期">{{ selectedAppointment.date }}</el-descriptions-item>
              <el-descriptions-item label="预约时间">{{ selectedAppointment.time }}</el-descriptions-item>
              <el-descriptions-item label="培训科目">{{ selectedAppointment.subject }}</el-descriptions-item>
              <el-descriptions-item label="学员姓名">{{ selectedAppointment.studentName }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ selectedAppointment.phone }}</el-descriptions-item>
              <el-descriptions-item label="教练姓名">{{ selectedAppointment.coachName }}</el-descriptions-item>
              <el-descriptions-item label="预约状态">
                <el-tag :type="getStatusType(selectedAppointment.status)">
                  {{ getStatusText(selectedAppointment.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="备注信息">{{ selectedAppointment.remark }}</el-descriptions-item>
            </el-descriptions>

            <div class="operation-buttons">
              <el-button
                v-if="selectedAppointment.status === 'pending'"
                type="success"
                @click="handleConfirm"
              >确认预约</el-button>
              <el-button
                v-if="['pending', 'confirmed'].includes(selectedAppointment.status)"
                type="danger"
                @click="handleCancel"
              >取消预约</el-button>
              <el-button
                v-if="selectedAppointment.status === 'confirmed'"
                type="primary"
                @click="handleComplete"
              >完成培训</el-button>
            </div>
          </div>
        </el-drawer>

        <!-- 新增预约抽屉 -->
        <el-drawer
          title="新增预约"
          v-model="dialogVisible"
          direction="rtl"
          size="50%"
        >
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
          >
            <el-form-item label="预约日期" prop="date">
              <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="选择日期"
                :disabled-date="disabledDate"
              />
            </el-form-item>
            <el-form-item label="预约时间" prop="time">
              <el-select v-model="form.time" placeholder="选择时间">
                <el-option
                  v-for="time in availableTimes"
                  :key="time"
                  :label="time"
                  :value="time"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="培训科目" prop="subject">
              <el-select v-model="form.subject" placeholder="选择科目">
                <el-option label="科目二" value="subject2" />
                <el-option label="科目三" value="subject3" />
              </el-select>
            </el-form-item>
            <el-form-item label="学员" prop="studentId">
              <el-select
                v-model="form.studentId"
                placeholder="选择学员"
                filterable
                remote
                :remote-method="searchStudents"
                :loading="studentLoading"
              >
                <el-option
                  v-for="student in students"
                  :key="student.id"
                  :label="student.name"
                  :value="student.id"
                >
                  <span>{{ student.name }}</span>
                  <span class="student-info">{{ student.phone }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="教练" prop="coachId">
              <el-select
                v-model="form.coachId"
                placeholder="选择教练"
                filterable
              >
                <el-option
                  v-for="coach in coaches"
                  :key="coach.id"
                  :label="coach.name"
                  :value="coach.id"
                >
                  <span>{{ coach.name }}</span>
                  <span class="coach-info">{{ getCoachTypeText(coach.type) }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit">确定</el-button>
            </span>
          </template>
        </el-drawer>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 当前选中的培训科目
const selectedSubject = ref('')

// 当前日期
const currentDate = ref(new Date())

// 预约数据
// 冲突检测
const checkConflicts = () => {
  const conflicts = []
  
  // 检查教练时间冲突
  appointments.value.forEach(app1 => {
    appointments.value.forEach(app2 => {
      if(app1.id !== app2.id && 
         app1.coachId === app2.coachId &&
         app1.date === app2.date &&
         app1.time === app2.time) {
        conflicts.push({
          type: 'coach',
          appointment1: app1,
          appointment2: app2
        })
      }
    })
  })
  
  // 检查学员时间冲突
  appointments.value.forEach(app1 => {
    appointments.value.forEach(app2 => {
      if(app1.id !== app2.id && 
         app1.studentId === app2.studentId &&
         app1.date === app2.date &&
         app1.time === app2.time) {
        conflicts.push({
          type: 'student',
          appointment1: app1,
          appointment2: app2
        })
      }
    })
  })
  
  if(conflicts.length > 0) {
    ElMessageBox.alert(`发现${conflicts.length}个预约冲突`, '冲突检测结果', {
      confirmButtonText: '确定',
      callback: () => {
        // 可以在这里显示冲突详情
      }
    })
  } else {
    ElMessage.success('未发现预约冲突')
  }
}

// 显示新建预约表单
const showCreateForm = ref(false)

const appointments = ref([
  {
    id: '1',
    date: '2024-03-15',
    time: '09:00-11:00',
    subject: '科目二',
    studentName: '张三',
    phone: '13800138000',
    coachName: '李教练',
    status: 'confirmed',
    remark: '倒车入库训练'
  },
  {
    id: '2',
    date: '2024-03-15',
    time: '14:00-16:00',
    subject: '科目二',
    studentName: '李四',
    phone: '13800138001',
    coachName: '李教练',
    status: 'pending',
    remark: '侧方停车训练'
  },
  {
    id: '3',
    date: '2024-03-16',
    time: '08:00-10:00',
    subject: '科目三',
    studentName: '王五',
    phone: '13800138002',
    coachName: '王教练',
    status: 'confirmed',
    remark: '路口左转训练'
  },
  {
    id: '4',
    date: '2024-03-16',
    time: '10:00-12:00',
    subject: '科目二',
    studentName: '赵六',
    phone: '13800138003',
    coachName: '李教练',
    status: 'completed',
    remark: '倒车入库训练'
  },
  {
    id: '5',
    date: '2024-03-17',
    time: '09:00-11:00',
    subject: '科目三',
    studentName: '孙七',
    phone: '13800138004',
    coachName: '王教练',
    status: 'confirmed',
    remark: '变更车道训练'
  },
  {
    id: '6',
    date: '2024-03-17',
    time: '14:00-16:00',
    subject: '科目二',
    studentName: '周八',
    phone: '13800138005',
    coachName: '张教练',
    status: 'pending',
    remark: '坡道定点停车训练'
  },
  {
    id: '7',
    date: '2024-03-18',
    time: '08:00-10:00',
    subject: '科目三',
    studentName: '吴九',
    phone: '13800138006',
    coachName: '王教练',
    status: 'cancelled',
    remark: '学员请假'
  },
  {
    id: '8',
    date: '2024-03-18',
    time: '10:00-12:00',
    subject: '科目二',
    studentName: '郑十',
    phone: '13800138007',
    coachName: '李教练',
    status: 'completed',
    remark: '坡道定点训练'
  },
  {
    id: '5',
    date: '2024-03-17',
    time: '14:00-16:00',
    subject: '科目三',
    studentName: '钱七',
    phone: '13800138004',
    coachName: '王教练',
    status: 'cancelled',
    remark: '变更车道训练'
  }
])

// 可选时间段
const availableTimes = [
  '08:00-10:00',
  '10:00-12:00',
  '14:00-16:00',
  '16:00-18:00',
  '19:00-21:00'
]

// 学员列表
const students = ref([])
const studentLoading = ref(false)

// 教练列表
const coaches = ref([
  { id: '1', name: '李教练', type: 'subject2' },
  { id: '2', name: '王教练', type: 'subject3' },
  { id: '3', name: '张教练', type: 'subject2' },
  { id: '4', name: '刘教练', type: 'subject3' },
  { id: '5', name: '陈教练', type: 'subject2' }
])

// 抽屉显示状态
const drawerVisible = ref(false)
const selectedAppointment = ref(null)

// 新增预约对话框
const dialogVisible = ref(false)
const formRef = ref(null)
const form = ref({
  date: '',
  time: '',
  subject: '',
  studentId: '',
  coachId: '',
  remark: ''
})

// 表单验证规则
const rules = {
  date: [{ required: true, message: '请选择预约日期', trigger: 'change' }],
  time: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
  subject: [{ required: true, message: '请选择培训科目', trigger: 'change' }],
  studentId: [{ required: true, message: '请选择学员', trigger: 'change' }],
  coachId: [{ required: true, message: '请选择教练', trigger: 'change' }]
}

// 获取日期预约
const getDateAppointments = (date) => {
  return appointments.value.filter(appointment => appointment.date === date)
}

// 获取预约样式类
const getAppointmentClass = (appointment) => {
  return {
    'status-pending': appointment.status === 'pending',
    'status-confirmed': appointment.status === 'confirmed',
    'status-completed': appointment.status === 'completed',
    'status-cancelled': appointment.status === 'cancelled'
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'confirmed': 'success',
    'completed': 'info',
    'cancelled': 'danger'
  }
  return typeMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'pending': '待确认',
    'confirmed': '已确认',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return textMap[status] || status
}

// 获取教练类型文本
const getCoachTypeText = (type) => {
  const typeMap = {
    'subject2': '科目二教练',
    'subject3': '科目三教练',
    'theory': '理论教练'
  }
  return typeMap[type] || type
}

// 禁用日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 选择今天
const selectToday = () => {
  currentDate.value = new Date()
}

// 改变月份
const changeMonth = (delta) => {
  const date = new Date(currentDate.value)
  date.setMonth(date.getMonth() + delta)
  currentDate.value = date
}

// 点击预约
const handleAppointmentClick = (appointment) => {
  selectedAppointment.value = appointment
  drawerVisible.value = true
}

// 搜索学员
const searchStudents = (query) => {
  if (query) {
    studentLoading.value = true
    // 模拟搜索
    setTimeout(() => {
      students.value = [
        { id: '1', name: '张三', phone: '13800138000' },
        { id: '2', name: '李四', phone: '13800138001' },
        { id: '3', name: '王五', phone: '13800138002' },
        { id: '4', name: '赵六', phone: '13800138003' },
        { id: '5', name: '钱七', phone: '13800138004' }
      ]
      studentLoading.value = false
    }, 500)
  } else {
    students.value = []
  }
}

// 新增预约
const handleAddAppointment = () => {
  form.value = {
    date: '',
    time: '',
    subject: selectedSubject.value,
    studentId: '',
    coachId: '',
    remark: ''
  }
  dialogVisible.value = true
}

// 确认预约
const handleConfirm = () => {
  ElMessageBox.confirm(
    '确认该预约吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 实现确认逻辑
    ElMessage.success('预约已确认')
    drawerVisible.value = false
  }).catch(() => {})
}

// 取消预约
const handleCancel = () => {
  ElMessageBox.confirm(
    '确认取消该预约吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 实现取消逻辑
    ElMessage.success('预约已取消')
    drawerVisible.value = false
  }).catch(() => {})
}

// 完成培训
const handleComplete = () => {
  ElMessageBox.confirm(
    '确认完成培训吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 实现完成逻辑
    ElMessage.success('培训已完成')
    drawerVisible.value = false
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      // 实现提交逻辑
      ElMessage.success('预约添加成功')
      dialogVisible.value = false
    }
  })
}
</script>

<style scoped>
.appointment-schedule {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 16px;
  align-items: center;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.calendar-title {
  font-size: 16px;
  font-weight: bold;
}

.calendar-cell {
  height: 100%;
  padding: 4px;
}

.date-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.appointment-list {
  font-size: 12px;
}

.appointment-item {
  margin: 2px 0;
  padding: 2px 4px;
  border-radius: 2px;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.appointment-item:hover {
  opacity: 0.8;
}

.status-pending {
  background-color: #e6a23c;
  color: #fff;
}

.status-confirmed {
  background-color: #67c23a;
  color: #fff;
}

.status-completed {
  background-color: #909399;
  color: #fff;
}

.status-cancelled {
  background-color: #f56c6c;
  color: #fff;
}

.operation-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.student-info,
.coach-info {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}
</style>